package com.pp.web.config;

import com.pp.common.filter.JwtAuthenticationFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 服务器端全局跨域配置: 跨域 & JWT
 * 通过Filter实现:
 * Filter -> DispatcherServlet -> Interceptor -> Controller
 */
@Configuration
public class GlobalWebMvcConfigurer implements WebMvcConfigurer {

    /**
     * 跨域配置
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }

    /**
     * 配置 CORS 跨域过滤器
     */
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilterRegistrationBean(){
        // 创建 config 对象 =>
        CorsConfiguration config = new CorsConfiguration();

        // 配置 config 对象 (跨域设置: url, method等) =>
        // 允许所有域名进行跨域调用
        config.addAllowedOrigin("*");
        // 允许跨越发送 cookie
        config.setAllowCredentials(true);
        // 允许放行全部原始头信息
        config.addAllowedHeader("*");
        // 允许所有请求方法跨域调用
        config.addAllowedMethod("*");

        // 创建 source 对象 =>
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        // 配置 source 对象 =>
        source.registerCorsConfiguration("/**", config);

        // 创建 filterRegistrationBean 对象 & 注册 CorsFilter 对象
        FilterRegistrationBean<CorsFilter> corsFilterRegistrationBean = new FilterRegistrationBean<>(
            new CorsFilter(source)
        );
        // 将 CorsFilter 优先等级设置为最高
        corsFilterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);

        return corsFilterRegistrationBean;
    }

    /**
     * 配置 JWT 验证过滤器
     */
    @Bean
    public FilterRegistrationBean<JwtAuthenticationFilter> jwtFilterRegistrationBean() {
        FilterRegistrationBean<JwtAuthenticationFilter> jwtFilterRegistrationBean = new FilterRegistrationBean<>();
        // 创建自定义的 JwtAuthenticationFilter 对象
        JwtAuthenticationFilter filter = new JwtAuthenticationFilter();
        // 将 JwtAuthenticationFilter 对象注册到过滤器链中
        jwtFilterRegistrationBean.setFilter(filter);
        // 返回 FilterRegistrationBean 对象给 Spring 容器
        return jwtFilterRegistrationBean;
    }

}
